package com.atguigu.gulimall.search.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constrant.EsConstant;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.to.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author centurion
 * @description: TODO
 * @date 2024/9/21
 */
@Slf4j
@Service
public class ElasticSaveServiceImpl implements ElasticSaveService{

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productUp(List<SkuEsModel> modelList) throws IOException {


        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        modelList.stream().forEach(item -> {
            //指定索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //指定id
            indexRequest.id(item.getSkuId().toString());
            //java对象传json字符串
            String jsonString = JSON.toJSONString(item);
            //指定文档内容
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        //批量保存到es
        BulkResponse bulk = this.restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架成功：{}", collect);

        return b;
    }
}
